<?php

namespace app\common\command;

use payment\{SlashService, WorldFirstService, AirwallexService};
use think\console\Command;
use think\console\input\Argument;
use think\console\Input;
use think\console\Output;
use think\facade\Log;


class QueryTransaction extends Command
{
    protected function configure()
    {
        $this->setName('query_transaction')
            ->addArgument('period', Argument::OPTIONAL, "day or month")
            ->setDescription('更新交易记录');
    }

    protected function execute(Input $input, Output $output)
    {
        date_default_timezone_set('UTC');

        $period = trim($input->getArgument('period'));
        if (!in_array($period, ['day', 'month'])) {
            $output->error('period 参数必须是 "day" 或 "month"');
            return;
        }
        Log::channel('query_transaction')->info("开始更新交易记录");
        $begin = time();

        $days = $period == 'day' ? 1 : 30;

        //空中云汇
//        $this->airwallex($days);

        //slash-12
        Log::channel('query_transaction')->info("SLASH-12");
        $this->slash($days,12);

        //slash-15
        Log::channel('query_transaction')->info("SLASH-15");
        $this->slash($days,15);

        //万里付非必要不打开，万里付有推送功能
//        $output->writeln("万里付");
//        $worldFirst = new WorldFirstService();
//        $this->worldfirst($days, $worldFirst);
//        $output->writeln("香港万里付");
//        $worldFirst = new WorldFirstService('worldfirst_hk');
//        $this->worldfirst($days, $worldFirst);

        $end = time();
        Log::channel('query_transaction')->info("更新交易记录完成");
        Log::channel('query_transaction')->info("耗时：" . ($end - $begin) . "秒");


    }

    //空中云汇交易记录
    private function airwallex($days)
    {
        try {
            $airwallex = new AirwallexService();
            $params = [
                'from_created_at' => date('c', strtotime("-$days days")),
                'to_created_at' => date('c'),
                'page_num' => 0,
                'page_size' => 200
            ];
            $has_more = true;

            while ($has_more) {
                $resp = $airwallex->getCardTransactions($params);

                if (isset($resp['items'])) {
                    foreach ($resp['items'] as $item) {
//                        trace($item);
                        airwallex_bill($item);
                    }
                    $params['page_num'] = $params['page_num'] + 1;
                    $has_more = $resp['has_more'];

                }
            }
        } catch (\Exception $e) {
            Log::channel('query_transaction')->error('失败原因:' . $e->getMessage());
            return false;
        }
    }

    //万里付卡交易记录
    private function worldfirst($days, $worldFirst)
    {
        $hasMore = true;
        $params = [
            'pageNumber' => 1,
            'pageSize' => 30,
            'startTime' => date('c', strtotime("-$days days")),
            'endTime' => date('c'),
        ];

        while ($hasMore) {
            $worldFirstResult = $worldFirst->getTransactionList($params);
            $resultStatus = $worldFirstResult['result']['resultStatus'] ?? '';
            // 检查是否有数据
            if ($resultStatus != 'S') {
                break;
            }
            file_put_contents('/dev/shm/worldfirst.log', date('Y-m-d H:i:s') . "\n");
            // 处理当前页数据
            foreach ($worldFirstResult['billList'] as $item) {
                $item['card_bin'] = $worldFirst->card_bin;
                Log::channel('query_transaction')->info(json_encode($item));
                file_put_contents('/dev/shm/worldfirst.log', json_encode($item) . "\n", FILE_APPEND);
                worldfirst_bill($item);
            }
            file_put_contents('/dev/shm/worldfirst.log', date('Y-m-d H:i:s') . "\n", FILE_APPEND);
            // 检查是否还有下一页
            $hasMore = $worldFirstResult['currentPageNumber'] < $worldFirstResult['totalPageNumber'];
            dump('第' . $worldFirstResult['currentPageNumber'] . "页");
            $params['pageNumber'] = $params['pageNumber'] + 1;
        }


    }

    //slash交易记录
    private function slash($days, $type = 12)
    {
//        if ($days == 1) $days = 3;
        $slash = new SlashService($type);
//        时间范围搜索有bug，此处屏蔽
        $params = [
//            'filter:from_date' => 1752148800000,
//            'filter:to_date' => 1752152399999,
//            'filter:status' => 'posted'
        ];
        $hasMore = true;
        $now = time();
        while ($hasMore) {
            $result = $slash->getTransaction($params);
            if (isset($result['items'])) {
                foreach ($result['items'] as $item) {
                    $timestamp = strtotime($item['date']);

                    if ($timestamp < $now - 86400 * $days) {
                        $hasMore = false;
                        break;
                    }
                    Log::channel('query_transaction')->info($item['cardId']??json_encode($item));
                    if (isset($item['cardId'])) {
//                        trace($item);
                        slash_bill($item);
                    }
                }
            }
            if (isset($result['metadata']['nextCursor'])) {
                $params['cursor'] = $result['metadata']['nextCursor'];
            } else {
                $hasMore = false;
            }
        }


    }


}